<template>
  <div class="common-container">
    <div class="header">
      <div class="header_left">

        <el-input v-model="search_val" placeholder="请输入楼层名称" clearable @clear="clearNickname" size="small"
          style="width: 220px;">
          <el-button class="el-input-group__append2" slot="append"
            :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'" @click="searchClick"></el-button>
        </el-input>

        <el-select size="small" style="width: 160px;margin-left: 15px;" clearable @change="changeOrgId"
          @visible-change="enterpriseChange" v-loadMore="loadMore2" v-model='buildingsName' placeholder='请选择建筑物'
          filterable remote :remote-method="remoteMethod2" @clear="clearBuildings">
          <el-option v-for='item in buildings' :label='item.name' :value='item.id' :key='item.id'>
          </el-option>
          <div class="div_box" v-loading="loading2" :style="loading2 ? '' : 'display: none;'"> </div>
        </el-select>

      </div>
      <div class="header_right">
        <el-button size="small" style="margin-left: 15px;" icon="el-icon-plus" @click="onAdd" v-if="orgInfo.orgId">新增</el-button>
        <el-dropdown @command="onDropdown">
          <el-button size="small" style="margin-left: 15px;">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <!-- <el-dropdown-item command="batch">批量操作</el-dropdown-item> -->
            <el-dropdown-item command="set">一键布防</el-dropdown-item>
            <el-dropdown-item command="remove">一键撤防</el-dropdown-item>
            <el-dropdown-item command="del">批量删除</el-dropdown-item>
            <!-- <el-dropdown-item command="alarmReceiver">设置接警人管理</el-dropdown-item>
                <el-dropdown-item command="del">批量删除</el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="content">
      <el-table :data="tableData" height="calc(100% - 65px)" class="table" @selection-change="batchSelect"
        :header-cell-style="headerStyle" row-key="id" ref="refMultipleTable" v-loading="loadingTable"
          element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)">
        <el-table-column align="center" type="selection" :reserve-selection="true" min-width="40">
        </el-table-column>
        <el-table-column align="center" label="序号" type="index" width="50">
        </el-table-column>
        <el-table-column align="center" prop="name" label="楼层">
        </el-table-column>
        <el-table-column align="center" prop="spaceCount" label="安装点数量">
          <template slot-scope="{ row }">
            <span @click="searchSpaceClick(row)" class="search_space">{{ row.spaceCount }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="isDefence" label="布防状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isDefence == 0" type="warning">已撤防</el-tag>
              <el-tag v-else type="success">已布防</el-tag>
            </template>
          </el-table-column> -->
        <el-table-column align="center" prop="orgName" label="联网单位" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="buildingName" label="建筑物" show-overflow-tooltip>
        </el-table-column>
        <el-table-column align="center" prop="management" label="操作" width="240" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="布防" placement="bottom">
              <i @click="onSet(scope.row)" class="iconfont anquan1 tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="撤防" placement="bottom">
              <i @click="onRemove(scope.row)" class="iconfont iconfontquxiaoshouquan tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
              <i @click="onEdit(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <i @click="onDel(scope.row.id)" class="iconfont shanchu tableBtnIcon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination :page.sync="page" :limit.sync="limit" :total="total" @pagination="SpaceManager" class="pagination">
      </pagination>

    </div>
    <addModel ref="refAdd" :orgInfo="orgInfo"></addModel>
    <editModel ref="refEdit" :getLocationInfo="getLocationInfo"></editModel>
    <batchModel ref="refBatch"></batchModel>
    <alarmReceiver ref="refAlarmReceiver"></alarmReceiver>
  </div>
</template>

<script>
import addModel from "./components/addModel.vue";
import editModel from "./components/editModel.vue";
import batchModel from "./components/batchModel.vue";
import alarmReceiver from "./components/alarmReceiver.vue";
import tableStyleMixin from "@mixin/table-style";
import loadMore from "@mixin/loadMore";
import Pagination from "@components/Pagination.vue";
import {
  reqSpaceManager,
  reqDel,
  reqBatchDefence,
  reqFloorBatchDelDel,
} from "@/api/api";
import { mapState } from "vuex";
import { jsonp } from 'vue-jsonp'//使用jsonp

export default {
  props: ['orgInfo'],
  name: "org-list",
  components: {
    Pagination,
    addModel,
    editModel,
    batchModel,
    alarmReceiver,
  },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      loadingSearch: false, //查询按钮loading
      search_val: "",
      page: 1,
      limit: 10,
      total: 0,
      tableData: [
      ],
      loadingTable:false,
      searchForm: {
        parentId: "",
      },
      getLocationInfo: {
        getLat: "",
        getLng: "",
        getAdd: "",
        province: "",
        city: "",
        area: "",
        provinceCityAreaValue: "",
      },
      batchDate: [],
      buildings: [],

      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
      selectedValue: '',
      buildingsName: '',
      orgName: "",
      buildingsName2: "",
      flag: true,
    };
  },
  mounted() {
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    //楼层初始化
    clearinit() {
      this.flag = true;
      this.buildings = []
      this.buildingsName = '';
      this.buildingsName2 = '';
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.searchForm.parentId = ''
      this.search_val = ""
      this.page = 1;
      this.limit = 10;
      this.tableData = [];
      this.total = 0;
      this.clearSelections() // 清空复选框√√
    },
    // 清空建筑物
    clearBuildings() {
      this.buildingsName = '';
      this.buildingsName2 = '';
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = []
      this.flag = true;
      // this.getBuildings()
    },
    // 远程搜索
    async remoteMethod2(query) {
      this.buildingsName = query; //保留输入的值
      this.buildingsName2 = query; //保留输入的值
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = []
      this.getBuildings()
    },
    // 建筑物操作
    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10)) return
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.getBuildings()
      this.loading2 = false;
    },
    // 建筑物列表
    async getBuildings() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 1,
        orgId: this.orgInfo.orgId,
        isStatistics: 0,
        name: this.buildingsName2
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total
      this.buildings = [...this.buildings, ...res.data.rows]
    },
    // 下拉请求列表
    enterpriseChange(val) {
      if (val && this.flag) {
        this.sysInstanceIndex2=1
        this.sysInstanceTotalPages2 =10
        this.buildings =[]
        this.getBuildings();  // 建筑物列表
        this.flag = false; //只执行一次
      }
    },

    // 选择建筑物
    changeOrgId(e) {
      this.searchForm.parentId = e
      this.page = 1;
      this.limit = 10;
      this.SpaceManager();
    },
    // 查看安装点
    searchSpaceClick(row) {
      // console.log(row);
      // this.$router.push({ name: "spacesManage", params: { id: row.id, name: row.name } });
      this.$emit('getSpaces',row)
    },
    // 清空
    clearNickname() {
      this.page = 1;
      this.limit = 10;
      this.SpaceManager();
    },
    //查询
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.SpaceManager();
      this.loadingSearch = false;
    },

    // 选择复选框批量添加联系人
    batchSelect(arr) {
      this.batchDate = [];
      // this.exportList = [];
      // this.exportList = arr;
      arr.forEach((c) => {
        this.batchDate.push(c.id);
      });
    },
    // 更多操作回调事件
    onDropdown(e) {
      if (this.batchDate.length <= 0) {
        this.$modal.notifyWarning("请勾选要操作的楼层");
        return;
      }
      switch (e) {
        case "batch":
          // console.log("batch");
          this.$refs.refBatch.dialogVisible = true;
          break;
        case "set":
          this.$confirm(
            "一键布防将对该楼层的所有安装点同时进行布防，确认后将更新该楼层下所有安装点为布防状态。",
            "楼层批量布防",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              const res = await reqBatchDefence({
                spaceIdList: this.batchDate,
                isDefence: 1,
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量设置布防成功!");
              this.SpaceManager();
              this.clearSelections(); //清空复选框
            })
            .catch(() => { });
          break;
        case "remove":
          this.$confirm(
            "一键撤防将对该楼层的所有安装点同时进行撤防，确认后将更新该楼层下所有安装点为撤防状态。",
            "楼层批量撤防",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              const res = await reqBatchDefence({
                spaceIdList: this.batchDate,
                isDefence: 0,
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量设置撤防成功!");
              this.SpaceManager();
              this.clearSelections(); //清空复选框
            })
            .catch(() => { });
          break;
        case "alarmReceiver":
          // console.log("alarmReceiver");
          this.$refs.refAlarmReceiver.dialogVisible = true;
          break;
        case "del":
          // console.log("del");
          this.$confirm("此操作将批量删除楼层, 是否继续?", "批量删除", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              const res = await reqFloorBatchDelDel({
                spaceIdList: this.batchDate,
                userId: this.user.userId
              });
              if (res.code !== 20000)
                return this.$modal.notifyWarning(res.message);
              this.$modal.notifySuccess("批量删除楼层成功!");
              this.SpaceManager();
              this.clearSelections(); //清空复选框
            })
            .catch(() => { });
          break;
      }
    },
    // 清空复选框√√
    clearSelections() {
      this.$refs.refMultipleTable.clearSelection();
    },
    // 新增
    onAdd() {
      // this.$refs.refAdd.SpaceManager();
      this.$refs.refAdd.dialogVisible = true;
    },
    onSet(row) {
      // 布防
      this.$confirm("确定布防该楼层吗？", "布防", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // row.isDefence = 1;
          // const res = await reqUpdate(row);
          const res = await reqBatchDefence({
            spaceIdList: [row.id],
            isDefence: "1",
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("布防成功!");
          this.SpaceManager();
        })
        .catch(() => { });
    },
    onRemove(row) {
      // 撤防
      this.$confirm("确定撤防该楼层吗？", "撤防", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // row.isDefence = 0;
          // const res = await reqUpdate(row);
          const res = await reqBatchDefence({
            spaceIdList: [row.id],
            isDefence: "0",
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("撤防成功!");
          this.SpaceManager();
        })
        .catch(() => { });
    },
    onEdit(item) {
      // console.log(item, "item");
      this.getLocationInfo = item;
      this.$refs.refEdit.dialogVisible = true;
    },
    onDel(id) {
      this.$confirm("此操作将永久删除该楼层, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await reqDel({
            id,
            userId: this.user.userId
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("删除楼层成功");
          this.SpaceManager();
        })
        .catch(() => { });
    },

    // 楼层列表
    async SpaceManager() {
      this.loadingTable=true;
      let res = await reqSpaceManager(this.page, this.limit, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        name: this.search_val,
        orgId: this.orgInfo.orgId,
        metaCode: 2,
        parentId: this.searchForm.parentId,
        isStatistics: 1
      });
      this.loadingTable=false;
      // console.log(res.data);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.tableData = res.data.rows;
      this.total = res.data.total;
    },
    // 建筑物点击楼层数量
    getFloor(e) {
      // console.log(e);
      this.flag = false;
      this.buildings = [{ id: e.name, name: e.name }]
      this.searchForm.parentId = e.id;
      this.buildingsName = e.name
      this.SpaceManager();
    },
  },
  async created() {
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");

// 查看关联安装点
.search_space {
  padding: 0 10px;
  cursor: pointer;

  &:hover {
    color: #7367f0;
  }
}

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 9999;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

</style>